package com.beici.waterghost.controller;

import com.alibaba.fastjson.JSONObject;
import com.beici.waterghost.model.node;
import com.beici.waterghost.model.resultes;
import com.beici.waterghost.model.user;
import com.beici.waterghost.service.impl.nodeServiceImpl;
import com.beici.waterghost.service.impl.userServiceImpl;
import com.beici.waterghost.service.userService;
import com.beici.waterghost.utils.contextUtils;
import com.beici.waterghost.utils.sendNoteUtils;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class userController {

    @Autowired
    private userServiceImpl userServer;
    @Autowired
    private nodeServiceImpl nodeService;
    @Autowired
    private sendNoteUtils sendNote;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 获取我的所有信息
     * @return 结果
     */
    @GetMapping("/myDetils")
    public resultes getMyDetils(){
        Map map = new HashMap();
        // 获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        user principal = (user) authentication.getPrincipal();
        resultes resultes = nodeService.quertyUserNodes(principal.getUserId());
        List<node> data = (ArrayList) resultes.getData();
        if (!data.isEmpty()){
            for (node datum : data) {
                datum.setUserHeader(principal.getUserHeader());
                datum.setUserName(principal.getUserName());
                // 将图片转为ArryList
                String[] split = datum.getNodeImages().split(",");
                datum.setArrImgs(split);
            }
        }else {
            data=null;
        }
        // 获取用户文章信息
        map.put("userInfo",principal);
        map.put("nodes",data);
        return resultes.success("获取成功",map);
    }

    /**
     * 获取对方所有信息
     * @return 结果
     */
    @GetMapping("/myDetils/{userId}")
    public resultes getFriendsDetils(@PathVariable("userId") Integer userId){
        Map map = new HashMap();
        // 获取用户信息
        resultes resultes = nodeService.quertyUserNodes(userId);
        user user = (com.beici.waterghost.model.user) userServer.selectUserDetailInfo(Long.valueOf(userId)).getData();
        List<node> data = (ArrayList) resultes.getData();
        if (!data.isEmpty()){
            for (node datum : data) {
                datum.setUserHeader(user.getUserHeader());
                datum.setUserName(user.getUserName());
                // 将图片转为ArryList
                String[] split = datum.getNodeImages().split(",");
                datum.setArrImgs(split);
            }
        }else {
            data=null;
        }
        // 获取用户文章信息
        map.put("userInfo",user);
        map.put("nodes",data);
        return resultes.success("获取成功",map);
    }
    @GetMapping("/getUserId")
    public Integer getUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        user principal = (user) authentication.getPrincipal();
        return principal.getUserId();
    }

    @GetMapping("/sendcode/{phone}")
    public resultes sendCode(@PathVariable("phone") String phone){
        // 正则匹配手机号
        String pattent="^1[3-9]\\d{9}$";
        boolean matches = Pattern.matches(pattent, String.valueOf(phone));
        if (!matches){
            return resultes.error("手机号码不正确");
        }
        // 查看当前手机号码是否已注册
        resultes resultes = userServer.phoneIsEntity(Long.valueOf(phone));
        if (resultes.getCode()!=200){
            return resultes;
        }
        String s = sendNote.gernerateCode();
        boolean b = sendNote.sendNoteUtils(new String[]{"86"+phone}, s);
        redisTemplate.opsForValue().set(phone,s,180, TimeUnit.SECONDS);
        return b?resultes.success("发送成功",true):resultes.error("发送失败");

    }

    @PutMapping("/reguser")
    public resultes regUser(String userName,String userPassword,Integer userSex,Long userPhone,String userHeader,String code){
        // 正则匹配手机号
        String pattent="^1[3-9]\\d{9}$";
        boolean matches = Pattern.matches(pattent, String.valueOf(userPhone));
        if (!matches){
            return resultes.error("手机号码不正确");
        }

        resultes resultes1 = verfityCode(userPhone, code);
        if (resultes1.getCode()==200){
            resultes resultes = userServer.regUser(userName,userPassword,userSex,userPhone,userHeader);
            return resultes;
        }
        return resultes1;
    }


    // 验证验证码是否合法
    private resultes verfityCode(Long phone,String code){
        if (code==null||code.length()<=0){
            return resultes.error("请填写验证码");
        }
        String s = "";
        try {
            s = redisTemplate.opsForValue().get(String.valueOf(phone));

        }catch (IllegalArgumentException r){
            return resultes.error("验证码已过期或未发送");
        }
        if (!code.equals(s)){
            return resultes.error("验证码不正确");
        }else {
            return resultes.success("",true);
        }
    }

    @PutMapping("/usermess/{mess}")
    public resultes updateUserMess(@PathVariable("mess") String mess){
        if (mess.length()>30){
            return resultes.error("内容长度超出30");
        }
        // 清洗数据
        boolean b = contextUtils.veifityContext(mess);
        if (!b){return resultes.error("内容包含敏感词汇");}
        user principal = (user) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userServer.updatUserMess(principal.getUserId(),mess);
    }
}
